<template>
  <div class="main">
    <NScrollbar>
      <NSpin :show="spinShow">
        <NSpace justify="center" style="margin-top: 10px;">
          <div style="height: 70px;line-height: 70px; font-size: 30px; font-weight: 700;color: red;font-family: 黑体">
            杭州国家版本馆文件阅办单</div>
          <img v-if="detailInfo.isUrgent == '加急'" src="@/assets/svg/urgent_logo.svg" style="width: 70px;height: 70px;" />
        </NSpace>
        <div style="width: 100%; display: flex; flex-direction: column; align-items: center">
          <div class="top_one_item">
            <div class="one_name">
              来文
              <br />
              单位
            </div>
            <div class="one_content">{{ detailInfo.unitCommunication }}</div>
            <div class="one_name">
              收文
              <br />
              日期
            </div>
            <div class="one_content"> {{ detailInfo.timeReceipt }}</div>
          </div>
          <div class="two_item">
            <div class="center_name">
              来文
              <br />
              标题
            </div>
            <div class="center_content">{{ detailInfo.titleCommunication }}</div>
          </div>
          <div class="four_item">
            <div class="center_name">吴雪勇</div>
            <div class="center_content">
              <NEllipsis :line-clamp="2">
                {{ infoA }}
                <template #tooltip>
                  <div style="max-width: 400px;">
                    {{ infoA }}
                  </div>
                </template>
              </NEllipsis>
            </div>
          </div>
          <div class="four_item">
            <div class="center_name">邬平福</div>
            <div class="center_content">
              <NEllipsis :line-clamp="2">
                {{ infoB }}

                <template #tooltip>
                  <div style="max-width: 400px;">
                    {{ infoB }}
                  </div>
                </template>
              </NEllipsis>
            </div>
          </div>
          <div class="five_item">
            <div class="center_name">张璞</div>
            <div class="center_content">
              <NEllipsis :line-clamp="2">
                {{ infoC }}

                <template #tooltip>
                  <div style="max-width: 400px;">
                    {{ infoC }}
                  </div>
                </template>
              </NEllipsis>
            </div>
          </div>
          <div class="six_item">
            <div class="center_name">
              <span>办公室</span>
              <span>拟办意见</span>
            </div>
            <div class="center_content">
              <NEllipsis :line-clamp="2">
                {{ infoD }}

                <template #tooltip>
                  <div style="max-width: 400px;">
                    {{ infoD }}
                  </div>
                </template>
              </NEllipsis>
            </div>
          </div>
          <div class="seven_item">
            <div class="center_name">部门阅文</div>
            <div class="center_content">
              <div class="center_four_content">
                <div class="four_content_name">办公室</div>
                <div class="four_content_content">
                  <NEllipsis :line-clamp="2">
                    {{ infoAA }}

                    <template #tooltip>
                      <div style="max-width: 400px;">
                        {{ infoAA }}
                      </div>
                    </template>
                  </NEllipsis>
                </div>
                <div class="four_content_name">展览部</div>
                <div class="four_content_content">
                  <NEllipsis :line-clamp="2">
                    {{ infoAAA }}

                    <template #tooltip>
                      <div style="max-width: 400px;">
                        {{ infoAAA }}
                      </div>
                    </template>
                  </NEllipsis>
                </div>
              </div>
              <div class="center_four_content">
                <div class="four_content_name">
                  <span>人力资源部</span>
                  <span>(机关党委)</span>
                </div>
                <div class="four_content_content">
                  <NEllipsis :line-clamp="2">
                    {{ infoBB }}

                    <template #tooltip>
                      <div style="max-width: 400px;">
                        {{ infoBB }}
                      </div>
                    </template>
                  </NEllipsis>
                </div>
                <div class="four_content_name">
                  <span>研究与交流</span>
                  <span>推广部</span>
                </div>
                <div class="four_content_content">
                  <NEllipsis :line-clamp="2">
                    {{ infoBBB }}

                    <template #tooltip>
                      <div style="max-width: 400px;">
                        {{ infoBBB }}
                      </div>
                    </template>
                  </NEllipsis>
                </div>
              </div>
              <div class="center_four_content">
                <div class="four_content_name">征集部</div>
                <div class="four_content_content">
                  <NEllipsis :line-clamp="2">
                    {{ infoCC }}

                    <template #tooltip>
                      <div style="max-width: 400px;">
                        {{ infoCC }}
                      </div>
                    </template>
                  </NEllipsis>
                </div>
                <div class="four_content_name">
                  <span>数字资源与</span>
                  <span>信息技术部</span>
                </div>
                <div class="four_content_content">
                  <NEllipsis :line-clamp="2">
                    {{ infoCCC }}

                    <template #tooltip>
                      <div style="max-width: 400px;">
                        {{ infoCCC }}
                      </div>
                    </template>
                  </NEllipsis>
                </div>
              </div>
              <div class="center_four_content">
                <div class="four_content_name">
                  <span>典藏部</span>
                  <span>(阅览部)</span>
                </div>
                <div class="four_content_content">
                  <NEllipsis :line-clamp="2">
                    {{ infoDD }}

                    <template #tooltip>
                      <div style="max-width: 400px;">
                        {{ infoDD }}
                      </div>
                    </template>
                  </NEllipsis>
                </div>
                <div class="four_content_name">
                  <span>行政管理部</span>
                  <span>(安全保卫部)</span>
                </div>
                <div class="four_content_content">
                  <NEllipsis :line-clamp="2">
                    {{ infoDDD }}

                    <template #tooltip>
                      <div style="max-width: 400px;">
                        {{ infoDDD }}
                      </div>
                    </template>
                  </NEllipsis>
                </div>
              </div>
            </div>
          </div>
        </div>
        <NSpace justify="center">
          <NButton type="primary" @click="handleExport" :loading="exportLoading" style="margin: 10px; width: 75px"
            v-if="userType == 'con'" ghost>
            导出
          </NButton>
        </NSpace>

        <div class="infoBox">
          <div class="line"></div>
          <div class="topTitle">阅办详情</div>
          <div class="basin-info">
            <div class="basin-left">
              <div class="box">
                <span>阅办类型：</span>
                <span>{{ detailInfo.readTypeName }}</span>
              </div>
              <div class="box">
                <span>是否加急：</span>
                <span>{{ detailInfo.isUrgent }}</span>
              </div>
            </div>
            <div class="basin-left">
              <div class="box">
                <span>附件：</span>
                <div style="display: flex;flex-wrap: wrap;gap: 15px 0;">
                  <VAttachments :attach-list="detailInfo.fileList"></VAttachments>
                </div>
              </div>
            </div>
          </div>

          <div class="topTitle">阅办流转</div>
          <div class="table">
            <NDataTable :bordered="false" :columns="columns" :data="tableData" :pagination="false" striped
              :rowKey="rowKey" style="min-height: 200px;font-size: 14px;" />
          </div>

          <div class="line"></div>

          <div class="topTitle">部门流转</div>
          <div class="tableA">
            <NDataTable :bordered="false" :columns="partcolumns" :data="tableDataA" :pagination="false" striped
              :rowKey="rowKey" style="min-height: 200px;font-size: 14px;" />
          </div>
        </div>
      </NSpin>
    </NScrollbar>
  </div>

  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">

          <template #icon>
            <img :src="VBackImg" style="width: 25px; height: 25px" />
          </template>
          返回
        </NButton>
      </NSpace>


      <NSpace justify="center">
        <NButton type="primary" style="margin-right: 40px;width: 78px" @click="transform(route.query?.id)"
          :loading="spinShow" v-if="!route.query.finish && ((detailInfo.nodeType == 'completed' && userType == 'con'
          ) || (userType == 'dep' && detailInfo.buttonType == 2 && !detailInfo.isOfficeOwner))" ghost>
          流转
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="margin-right: 40px;width: 78px" @click="urge(route.query?.id)" :loading="spinShow"
          v-if="!route.query.finish && ((detailInfo.nodeType == 'pending' && userType == 'con')
            || (userType == 'dep' && detailInfo.buttonType == 1))" ghost>
          催办
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="margin-right: 40px;width: 78px" @click="finish(route.query?.id)"
          :loading="spinShow" v-if="!route.query.finish && userType == 'con' && detailInfo.status == 'pending'" ghost>
          办结
        </NButton>
      </NSpace>


      <NSpace justify="center">
        <NButton type="primary" style="margin-right: 40px;width: 78px" @click="handle(route.query?.id)"
          :loading="spinShow"
          v-if="!route.query.finish && ((userType == 'other' && detailInfo.status == 'pending') || userType == 'dep')"
          ghost>
          办理
        </NButton>
      </NSpace>

    </div>

  </FixedAction>
  <!-- 流转 -->
  <NModal :auto-focus="false" v-model:show="transformVisiable" @close="transformVisiable = false">
    <VScope @close="transformVisiable = false" @scopeSubmit="getScopeList" :defaultList="scopeList" :readFlat="true"
      :flat="true" />
  </NModal>

  <!-- 催办 -->
  <NModal :auto-focus="false" v-model:show="urgeVisiable">
    <VDialogContent @close="urgeVisiable = false" @submit="againurge" title="催办提示">
      <div style="width: 300px; height: 100px; text-align: center; line-height: 100px">
        您确定要催办此阅办吗？
      </div>
    </VDialogContent>
  </NModal>


  <!-- 阅办未处理提示 -->
  <NModal :auto-focus="false" v-model:show="beforeHandleVisiable">
    <VDialogContentOnlySure @close="beforeHandleVisiable = false" @submit="beforeHandle" title="提示">
      <div>
        本次阅办流程还有以下用户未处理:
      </div>
      <div style="width: 300px; height: 100px; text-align: center; line-height: 100px">
        {{ beforeBack }}
      </div>
    </VDialogContentOnlySure>
  </NModal>


  <!-- 办理 -->
  <NModal :auto-focus="false" v-model:show="handleVisiable">
    <VDialogContent @close="handleVisiable = false" @submit="againhandle" title="办理提示">
      <!-- <NSpace>
        意见：
        <NInput type="textarea" placeholder="请输入" rows="1" v-model:value="comment" style="min-height: 100px; width: 300px"
          clearabled />
      </NSpace> -->
      <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="commentRule" :label-width="65"
        :model="formComment">
        <NFormItem label="意见:" path="comment">
          <NInput type="textarea" placeholder="请输入" rows="1" v-model:value="formComment.comment"
            style="min-height: 100rem; width: 300rem" clearabled />
        </NFormItem>
      </NForm>
    </VDialogContent>
  </NModal>

  <!-- 办理反馈弹窗 -->
  <NModal :auto-focus="false" v-model:show="finishBackVisiable">
    <VDialogContentOnlySure @close="finishBackVisiable = false" @submit="thirdhandle" title="办理信息提示">
      <div style="width: 300px; height: 100px; text-align: center; line-height: 100px">
        {{ finishBack }}
      </div>
    </VDialogContentOnlySure>
  </NModal>

  <!-- 办结 -->
  <NModal :auto-focus="false" v-model:show="finishVisiable">
    <VDialogContent @close="finishVisiable = false" @submit="againfinish" title="办结提示">
      <div style="width: 300px; height: 100px; text-align: center; line-height: 100px">
        您确定要完结此阅办吗？
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import {
  NSpace,
  NButton,
  useMessage,
  NDataTable,
  NSpin,
  NModal,
  NEllipsis,
  NScrollbar,
  NInput,
  type DataTableColumns
} from 'naive-ui'
import VAttachments from '@/views/OA/Common/Attachments.vue'
import FixedAction from '@/components/FixedAction.vue'
import VBackImg from '@/assets/images/back.png'
import VScope from '@/views/OA/Common/Scope.vue'
import { useTagStore } from '@/stores/layout'
import router from '@/router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import VDialogContentOnlySure from '@/views/OA/Common/DialogContentOnlySure.vue'


const message = useMessage()
const route = useRoute()
const tags = useTagStore().tags

const spinShow = ref(false)


// 获取当前用户分身
// 机要：con
// 部门负责人：dep
// 普通员工：other
const userType: any = ref('')
const queryUser = async () => {
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'userInfo',
  })
  if (error) return message.error(error.message)
  if (res.code) return message.error(res.msg)
  userType.value = res.data
}
queryUser()

//导出
const exportLoading = ref(false)
function download(headers: any, data: any, name?: any) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '.docx'
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
async function handleExport() {
  exportLoading.value = true
  const [error, res, headers] = await sendRequest({
    module: 'readingandprocessing',
    api: 'Export',
    override: {
      params: {
        id: route.query.id
      }
    }
  })
  if (error) return message.error(error.message), (exportLoading.value = false)
  download(headers, res, '杭州国家版本馆文件阅办单')
  message.success('导出成功')
  exportLoading.value = false
}

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}

//表格-阅办流转
const rowKey: any = (row: any) => row.id || ''
const columns: DataTableColumns = [
  {
    title: '部门',
    key: 'deptName',
    width: 100
  },
  {
    title: '人员',
    key: 'userName',
    width: 50
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 100
  },
  {
    title: '处理时间',
    key: 'updateTime',
    width: 100
  },
  {
    title: '结果',
    key: 'result',
    width: 50,
    render(e: any) {
      return e.result == 1 ? '已处理' : '未处理'
    }
  },
  {
    title: '意见',
    key: 'comment',
    width: 100,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400px'
        }
      }
    }
  }
]

//表格-部门流转
const partcolumns: DataTableColumns = [
  {
    title: '部门',
    key: 'deptName',
    width: 100
  },
  {
    title: '人员',
    key: 'userName',
    width: 50
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 100
  },
  {
    title: '处理时间',
    key: 'updateTime',
    width: 100
  },
  {
    title: '意见',
    key: 'comment',
    width: 150,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400px'
        }
      }
    }
  }
]
const detailInfo = ref<any>({})
const tableData = ref([])
const tableDataA = ref([])

const infoA = ref()
const infoB = ref()
const infoC = ref()
const infoD = ref()

const infoAA = ref()
const infoBB = ref()
const infoCC = ref()
const infoDD = ref()

const infoAAA = ref()
const infoBBB = ref()
const infoCCC = ref()
const infoDDD = ref()
//详情
const getReturnInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'Item',
    uri: {
      id: route.query?.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  detailInfo.value = res.data
  tableData.value = detailInfo.value.conData
  tableDataA.value = detailInfo.value.noConData
  const tmp: any = detailInfo.value.specialOpinions
  infoA.value = tmp.find((i: any) => i.name == '吴雪勇')?.specialOpinion
  infoB.value = tmp.find((i: any) => i.name == '邬平福')?.specialOpinion
  infoC.value = tmp.find((i: any) => i.name == '张璞')?.specialOpinion
  infoD.value = tmp.find((i: any) => i.name == '办公室拟办意见')?.specialOpinion

  infoAA.value = tmp.find((i: any) => i.name == '办公室（财务部）')?.specialOpinion
  infoBB.value = tmp.find((i: any) => i.name == '人力资源部（机关党委）')?.specialOpinion
  infoCC.value = tmp.find((i: any) => i.name == '征集部')?.specialOpinion
  infoDD.value = tmp.find((i: any) => i.name == '典藏部（阅览部）')?.specialOpinion

  infoAAA.value = tmp.find((i: any) => i.name == '展览部')?.specialOpinion
  infoBBB.value = tmp.find((i: any) => i.name == '研究与交流推广部')?.specialOpinion
  infoCCC.value = tmp.find((i: any) => i.name == '数字资源与信息技术部')?.specialOpinion
  infoDDD.value = tmp.find((i: any) => i.name == '行政管理部（安全保卫部）')?.specialOpinion

  spinShow.value = false
}

//流转
const transformVisiable = ref(false)
const transform = (val: any) => {
  transformVisiable.value = true
  itemId.value = val
}

//同伴
const scopeList = ref()

// 发布范围选择
const scopeOrPeopleList = ref()
const getScopeList = async (v: any) => {
  scopeOrPeopleList.value = v
  transformVisiable.value = false
  //调接口
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'Transform',
    override: {
      data: {
        officeId: itemId.value,
        scopeOrPeopleList: scopeOrPeopleList.value
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code) {
    message.error(res.msg)
  } else {
    message.success(res.msg)
    transformVisiable.value = false
    await getReturnInfo()
    goBack()
  }
}

//催办
const urgeVisiable = ref(false)
const urge = (val: any) => {
  urgeVisiable.value = true
  itemId.value = val
}
const againurge = async () => {
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'Urge',
    override: {
      data: {
        officeId: itemId.value
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code) {
    message.error(res.msg)
  } else {
    message.success(res.msg)
    urgeVisiable.value = false
    await getReturnInfo()
    goBack()
  }
}

//办理表单校验
const formComment = reactive({
  comment: '已阅',
})

const commentRule = {
  comment: {
    required: true,
    trigger: ['input', 'change'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写办理意见')
      if (value.length > 100) return new Error('办理意见不得超过100字')
      return true
    }
  }
}

//办理
const handleVisiable = ref(false)
// const comment = ref('已阅')
const handle = async (val: any) => {
  itemId.value = val
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'BeforeHandle',
    override: {
      data: {
        officeId: val
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code) return
  if (res.data == '' || !res.data) {
    handleVisiable.value = true
  } else {
    beforeBack.value = res.data
    beforeHandleVisiable.value = true
  }
}


//办理前
const beforeHandleVisiable = ref(false)
const beforeBack = ref('')
const beforeHandle = () => {
  beforeHandleVisiable.value = false
}

//办理返回信息弹窗
const finishBack: any = ref('')
const finishBackVisiable = ref(false)
const thirdhandle = async () => {
  finishBackVisiable.value = false
  await goRun()
}
const itemId = ref()
const againhandle = async () => {
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'Handle',
    override: {
      data: {
        officeId: route.query?.id,
        comment: formComment.comment
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code) {
    finishBack.value = res.msg
    handleVisiable.value = false
    finishBackVisiable.value = true
  } else {
    message.success(res.msg)
    handleVisiable.value = false
    await goRun()
  }
}

const goRun = () => {
  router.push({ path: '/OA/ReadingAndProcessing/ReadList' })
}

//办结
const finishVisiable = ref(false)
const finish = (val: any) => {
  finishVisiable.value = true
  itemId.value = val
}

const againfinish = async () => {
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'Finish',
    override: {
      data: {
        officeId: itemId.value
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code) {
    message.error(res.msg)
  } else {
    message.success(res.msg)
  }
  finishVisiable.value = false
  await getReturnInfo()
  goBack()
}

watch(
  () => route,
  () => {
    if (route.path == '/OA/ReadingAndProcessing/ReadingDetail' && route.query.id) getReturnInfo()
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;

  @mixin commonHight($height) {
    height: auto;
    min-height: $height;
    font-size: 18px;
  }

  @mixin commonFlex() {
    display: flex;
    justify-content: center;
    align-items: center;
    word-break: break-all;
    padding: 10px;
  }

  .top_one_item {
    display: flex;
    width: 700px;
    border: 1px solid red;
    font-weight: 700;
    font-family: 'GB2312';
    @include commonHight(80px);

    .one_name {
      flex: 0 0 15%;
      border-left: 1px solid red;
      @include commonFlex;
      color: red;

      &:nth-of-type(1) {
        border-left: none;
      }
    }

    .one_content {
      flex: 0 0 35%;
      border-left: 1px solid red;
      word-break: break-all;
      @include commonFlex;
    }
  }

  .two_item,
  .three_item,
  .four_item,
  .five_item,
  .six_item,
  .seven_item {
    display: flex;
    width: 700px;
    border: 1px solid red;
    border-top: none;
    font-weight: 700;
    font-family: 'GB2312';
    @include commonHight(80px);

    .center_name {
      flex: 0 0 15%;
      flex-direction: column;
      color: red;
      @include commonFlex;
    }

    .center_content {
      flex: 0 0 85%;
      border-left: 1px solid red;
      flex-direction: column;
      @include commonFlex;

      .center_four_content {
        display: flex;
        width: 100%;
        flex: 0 0 25%;
        border-top: 1px solid red;

        &:nth-of-type(1) {
          border-top: none;
        }

        .four_content_name {
          flex: 0 0 22%;
          flex-direction: column;
          border-left: 1px solid red;
          @include commonFlex;
          color: red;

          &:nth-of-type(1) {
            border-left: none;
          }
        }

        .four_content_content {
          flex: 0 0 28%;
          border-left: 1px solid red;
          word-break: break-all;

          @include commonFlex;
        }
      }
    }
  }

  .three_item {
    @include commonHight(150px);
  }

  .four_item,
  .five_item,
  .six_item {
    @include commonHight(100px);
  }

  .seven_item {
    @include commonHight(320px);

    .center_content {
      padding: 0px;
    }
  }
}

.infoBox {
  padding: 40px;
}

.topTitle {
  font-size: 22px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  color: #5fb17f;
  margin-bottom: 10px;
}

.basin-info {
  display: flex;
  width: 100%;
  height: auto;
  border-bottom: 1px dashed #bc9e70;
  margin-bottom: 10px;

  .basin-left {
    flex: 0 0 40%;
  }

  .box {
    display: flex;
    margin-bottom: 10px;
    font-size: 16px;

    span:first-child {
      display: inline-block;
      width: 120px;
    }

    span:last-child {
      display: inline-block;
      flex: 1;
    }
  }

  .box:last-child {
    margin-bottom: 20px;
  }
}

.table {
  width: 80%;
  background-color: #e1e1e1;
}

.tableA {
  width: 80%;
  background-color: #e1e1e1;
  margin-bottom: 70px;
}

.line {
  margin: 25px 0 15px;
  border-bottom: 1px dashed #bc9e70;
}
</style>
